﻿using Microsoft.Extensions.Logging;
using Sayook.Framework.DbCore.CreateSqlString;
using Sayook.Framework.DbCore.DbConnection;
using System;
using System.Data;

namespace Sayook.Framework.DbCore.DbContext
{
    /// <summary>
    /// 事务访问数据库基类
    /// </summary>
    public abstract class TransactionDbContext : DbContext
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connProvider">数据库连接</param>
        /// <param name="logger">日志</param>
        public TransactionDbContext(IDbConnectionProvider connProvider, ILogger<TransactionDbContext> logger) : base(connProvider, logger) { }

        #region Transaction 操作

        /// <summary>
        /// 事务子操作
        /// </summary>
        private Action<IDbConnection, IDbTransaction> Actions;

        /// <summary>
        /// 添加事务
        /// </summary>
        /// <param name="action">子操作</param>
        /// <returns>BaseDbContext</returns>
        public TransactionDbContext AddTransaction(Action<IDbConnection, IDbTransaction> action)
        {
            Actions += action;
            return this;
        }

        /// <summary>
        /// 执行事务
        /// </summary>
        /// <returns>执行结果 true:成功;false:失败</returns>
        public bool ExeTran()
        {
            using var dbConnection = _connProvider.Create(DbConnectionString);
            dbConnection.Open();
            using IDbTransaction dbTransaction = dbConnection.BeginTransaction();
            try
            {
                Actions(dbConnection, dbTransaction);
                dbTransaction.Commit();
                return true;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "DbContext.ExeTransaction异常：{0}", ex.Message);
                dbTransaction.Rollback();
                return false;
            }
            finally 
            {
                dbConnection.Close();
                Actions = null;
            }
        }

        #endregion Transaction 操作
    }
}